<!-- 童晓白修改 2025-08-16 14:00-->
<template>
  <view class="mytask-page">
    <!-- 顶部品牌与用户 -->
    <view class="header-bar-new">
      <view class="brand">SKILLITH</view>
      <view class="user-info">
        <image :src="getAvatarUrl(userStore.profile?.avatarUrl)" class="avatar" @error="handleAvatarError" />
        <text class="nickname">{{ userStore.profile?.nickname }}</text>
      </view>
    </view>
    <!-- 搜索区 -->
    <view class="search-area">
      <view class="search-container">
        <input v-model="filters.keyword" type="text" placeholder="搜索任务、公司、技能..." class="search-input" @confirm="onSearch">
        <button class="search-btn" @tap="onSearch">
          <image src="/static/images/search.png" class="rocket-icon" :class="{shake: rocketShake}" />
          <text>搜索</text>
        </button>
      </view>
    </view>
    <!-- 发布任务按钮 -->
    <!-- #ifdef H5 -->
    <view class="publish-task-area">
      <button class="publish-task-btn" @click="goToPublishTask">
        <span class="publish-icon">+</span>
        <span class="publish-text">发布任务</span>
      </button>
    </view>
    <!-- #endif -->
    <!-- #ifdef MP-WEIXIN -->
    <view class="publish-task-area">
      <button class="publish-task-btn" @tap="goToPublishTask">
        <text class="publish-icon">+</text>
        <text class="publish-text">发布任务</text>
      </button>
    </view>
    <!-- #endif -->
    <!-- 筛选区：横向滑动 chip -->
    <!-- #ifdef H5 -->
    <view class="scrollable-filters">
      <!-- 状态 chips -->
      <view
        class="filter-chip"
        :class="{ active: filters.status === '' }"
        @click="setStatus('')"
      >全部状态</view>
      <view
        class="filter-chip"
        :class="{ active: filters.status === '0' }"
        @click="setStatus('0')"
      >待审核</view>
      <view
        class="filter-chip"
        :class="{ active: filters.status === '1' }"
        @click="setStatus('1')"
      >已发布</view>
      <view
        class="filter-chip"
        :class="{ active: filters.status === '2' }"
        @click="setStatus('2')"
      >进行中</view>
      <view
        class="filter-chip"
        :class="{ active: filters.status === '3' }"
        @click="setStatus('3')"
      >已完成</view>
      <!-- 类型 chips -->
      <view
        class="filter-chip"
        :class="{ active: filters.type === '' }"
        @click="setType('')"
      >全部类型</view>
      <view
        class="filter-chip"
        :class="{ active: filters.type === 'individual' }"
        @click="setType('individual')"
      >个人任务</view>
      <view
        class="filter-chip"
        :class="{ active: filters.type === 'team' }"
        @click="setType('team')"
      >组队任务</view>
      <!-- 区域选择 chip -->
      <view
        class="filter-chip"
        :class="{ active: selectedProvince || selectedCity || selectedDistrict }"
        @click="openRegionSelector"
      >区域：{{ selectedProvince || '全国' }}{{ selectedCity ? ' ' + selectedCity : '' }}{{ selectedDistrict ? ' ' + selectedDistrict : '' }}</view>
      <!-- 类型选择 chip（三级联动） -->
      <view
        class="filter-chip"
        :class="{ active: selectedField || selectedCategory || selectedDirection }"
        @click="openTypeSelector"
      >类型：{{ getTypeLabel }}</view>
    </view>
    <!-- #endif -->
    <!-- #ifdef MP-WEIXIN -->
    <view class="scrollable-filters">
      <!-- 状态 chips -->
      <view
        class="filter-chip"
        :class="{ active: filters.status === '' }"
        @tap="setStatus('')"
      ><text>全部状态</text></view>
      <view
        class="filter-chip"
        :class="{ active: filters.status === '0' }"
        @tap="setStatus('0')"
      ><text>待审核</text></view>
      <view
        class="filter-chip"
        :class="{ active: filters.status === '1' }"
        @tap="setStatus('1')"
      ><text>已发布</text></view>
      <view
        class="filter-chip"
        :class="{ active: filters.status === '2' }"
        @tap="setStatus('2')"
      ><text>进行中</text></view>
      <view
        class="filter-chip"
        :class="{ active: filters.status === '3' }"
        @tap="setStatus('3')"
      ><text>已完成</text></view>
      <!-- 类型 chips -->
      <view
        class="filter-chip"
        :class="{ active: filters.type === '' }"
        @tap="setType('')"
      ><text>全部类型</text></view>
      <view
        class="filter-chip"
        :class="{ active: filters.type === 'individual' }"
        @tap="setType('individual')"
      ><text>个人任务</text></view>
      <view
        class="filter-chip"
        :class="{ active: filters.type === 'team' }"
        @tap="setType('team')"
      ><text>组队任务</text></view>
      <!-- 区域选择 chip -->
      <view
        class="filter-chip"
        :class="{ active: selectedProvince || selectedCity || selectedDistrict }"
        @tap="openRegionSelector"
      ><text>区域：{{ selectedProvince || '全国' }}{{ selectedCity ? ' ' + selectedCity : '' }}{{ selectedDistrict ? ' ' + selectedDistrict : '' }}</text></view>
      <!-- 类型选择 chip（三级联动） -->
      <view
        class="filter-chip"
        :class="{ active: selectedField || selectedCategory || selectedDirection }"
        @tap="openTypeSelector"
      ><text>类型：{{ getTypeLabel }}</text></view>
    </view>
    <!-- #endif -->
	  <!-- 类型选择弹窗 -->
	  <!-- #ifdef H5 -->
	    <view v-if="showTypeSelector" class="region-popup-mask" @click.self="showTypeSelector = false">
	      <view class="region-popup" @click.stop>
	        <view class="region-picker-header">
	          <text class="region-picker-cancel" @tap="showTypeSelector = false">取消</text>
	          <text class="region-picker-title">请选择类型</text>
	          <text class="region-picker-confirm" @tap="confirmType">确认</text>
	        </view>
	      </view>
	    </view>
	  <!-- #endif -->
	  <!-- #ifdef MP-WEIXIN -->
	    <view v-if="showTypeSelector" class="region-popup-mask" @tap.self="showTypeSelector = false">
	      <view class="region-popup" @tap.stop>
	        <view class="region-picker-header">
	          <text class="region-picker-cancel" @tap="showTypeSelector = false">取消</text>
	          <text class="region-picker-title">请选择类型</text>
	          <text class="region-picker-confirm" @tap="confirmType">确认</text>
	        </view>
	        <view class="region-columns">
	          <!-- 领域 -->
	          <view class="region-list-wrapper">
	            <view class="gradient-top"></view>
	            <view class="region-list">
	              <view :class="{active: tempField === ''}" @tap="selectTempField('')"><text>全部</text></view>
	              <view v-for="field in fields" :key="field.code" :class="{active: field.code === tempField}" @tap="selectTempField(field.code)"><text>{{ field.name }}</text></view>
	            </view>
	            <view class="gradient-bottom"></view>
	          </view>
	          <!-- 大类 -->
	          <view class="region-list-wrapper">
	            <view class="gradient-top"></view>
	            <view class="region-list">
	              <view :class="{active: tempCategory === ''}" @tap="selectTempCategory('')"><text>全部</text></view>
	              <view v-for="category in (fields.find(f => f.code === tempField)?.subcategories || [])" :key="category.code" :class="{active: category.code === tempCategory}" @tap="selectTempCategory(category.code)"><text>{{ category.name }}</text></view>
	            </view>
	            <view class="gradient-bottom"></view>
	          </view>
	          <!-- 方向 -->
	          <view class="region-list-wrapper">
	            <view class="gradient-top"></view>
	            <view class="region-list">
	              <view :class="{active: tempDirection === ''}" @tap="selectTempDirection('')"><text>全部</text></view>
	              <view v-for="direction in ((() => { const f = fields.find(f => f.code === tempField); const c = f?.subcategories.find(c => c.code === tempCategory); return c?.directions || []; })())" :key="direction.code" :class="{active: direction.code === tempDirection}" @tap="selectTempDirection(direction.code)"><text>{{ direction.name }}</text></view>
	            </view>
	            <view class="gradient-bottom"></view>
	          </view>
	        </view>
	      </view>
	    </view>
	  <!-- #endif -->

	
	  <!-- 区域选择弹窗 -->
      <view v-if="showRegionSelector" class="region-popup-mask" @click.self="showRegionSelector = false">
        <view class="region-popup" @click.stop>
          <view class="region-picker-header">
            <span class="region-picker-cancel" @click="showRegionSelector = false">取消</span>
            <span class="region-picker-title">请选择地区</span>
            <span class="region-picker-confirm" @click="confirmRegion">确认</span>
          </view>
          <view class="region-columns">
            <view class="region-list-wrapper">
              <view class="gradient-top"></view>
                             <view class="region-list">
                 <view :class="{active: tempProvince === ''}" @tap="selectTempProvince('')"><text>全部</text></view>
                 <view v-for="province in provinces" :key="province" :class="{active: province === tempProvince}" @tap="selectTempProvince(province)"><text>{{ province }}</text></view>
               </view>
              <view class="gradient-bottom"></view>
            </view>
            <view class="region-list-wrapper">
              <view class="gradient-top"></view>
              <ul class="region-list">
                <li :class="{active: tempCity === ''}" @click="selectTempCity('')">全部</li>
                <li v-for="city in (geoData.find(p => p.name === tempProvince)?.cities.map(c => c.name) || [])" :key="city" :class="{active: city === tempCity}" @click="selectTempCity(city)">{{ city }}</li>
              </ul>
              <view class="gradient-bottom"></view>
            </view>
            <view class="region-list-wrapper">
              <view class="gradient-top"></view>
              <ul class="region-list">
                <li :class="{active: tempDistrict === null || tempDistrict === ''}" @click="selectTempDistrict(null)">全部</li>
                <li v-for="district in ((() => { const p = geoData.find(p => p.name === tempProvince); const c = p?.cities.find(c => c.name === tempCity); return c?.districts || []; })())" :key="district.adcode" :class="{active: district.name === tempDistrict?.name}" @click="selectTempDistrict(district)">{{ district.name }}</li>
              </ul>
              <view class="gradient-bottom"></view>
            </view>
          </view>
        </view>
      </view>
	  
	  
	
    <!-- 滑动标签栏 -->
    <view class="tab-bar-new">
      <view :class="['tab-item-new', tab==='published' ? 'active' : '']" @click="tab='published';fetchTasks()">
        <img src="/static/images/planet.png" class="tab-icon" :class="{active: tab==='published'}" />
        我发布的任务
        <view v-if="tab==='published'" class="tab-underline-new"></view>
      </view>
      <view :class="['tab-item-new', tab==='challenge' ? 'active' : '']" @click="tab='challenge';fetchTasks()">
        <img src="/static/images/right.png" class="tab-icon" :class="{active: tab==='challenge'}" />
        我挑战的任务
        <view v-if="tab==='challenge'" class="tab-underline-new"></view>
      </view>
    </view>
    <!-- 任务列表 -->
    <view v-if="loading" class="loading-spinner"><span class="spinner"></span></view>
    <view v-else>
      <view v-if="tasks.length" class="task-list-new">
        <view v-for="task in tasks" :key="task.taskId" class="task-card" @click="goToTaskDetail(task.taskId)" @mousedown="cardActive = task.taskId" @mouseup="cardActive = null" :style="cardActive === task.taskId ? 'transform:scale(0.98);' : ''">
          <view class="task-card-header">
            <h3 class="task-title-new">{{ task.title }}</h3>
            <view class="task-salary-new">{{ formatReward(task.reward) }}元</view>
          </view>
          <p class="task-desc-new">{{ task.description.length > 100 ? task.description.substring(0, 100) + '...' : task.description }}</p>
          
          <!-- 任务时间信息 -->
          <view class="task-time-info">
            <div class="time-item">
              <span class="time-icon">📅</span>
              <span class="time-label">发布时间：</span>
              <span class="time-value">{{ formatDateTime(task.publishTime) }}</span>
            </div>
            <div class="time-item">
              <span class="time-icon">⏰</span>
              <span class="time-label">截止时间：</span>
              <span class="time-value">{{ formatDateTime(task.deadline) }}</span>
            </div>
            <div class="time-item" v-if="task.challengeStartTime">
              <span class="time-icon">🎯</span>
              <span class="time-label">接取时间：</span>
              <span class="time-value">{{ formatDateTime(task.challengeStartTime) }}</span>
            </div>
             <div class="time-item" v-if="task.challengeEndTime">
               <span class="time-icon">✅</span>
               <span class="time-label">完成时间：</span>
               <span class="time-value">{{ formatDateTime(task.challengeEndTime) }}</span>
             </div>
          </view>
          
          <!-- 挑战类型信息（仅在我挑战的任务中显示） -->
          <view v-if="tab === 'challenge'" class="challenge-type-info">
            <view class="challenge-type-card" :class="getChallengeTypeClass(task.challengeType)">
              <view class="challenge-type-header">
                <view class="challenge-type-icon">
                  <text v-if="task.challengeType === 'single'">👤</text>
                  <text v-else-if="task.challengeType === 'team'">👥</text>
                  <text v-else>❓</text>
                </view>
                <text class="challenge-type-title">{{ getChallengeTypeText(task.challengeType) }}</text>
                <view class="challenge-type-badge" :class="getChallengeTypeBadgeClass(task.challengeType)">
                  {{ getChallengeTypeBadgeText(task.challengeType) }}
                </view>
              </view>
              
              <!-- 组队挑战详细信息 -->
              <view v-if="task.challengeType === 'team'" class="team-details">
                <view class="team-role-info">
                  <text class="role-label">我的角色：</text>
                  <text class="role-value" :class="getRoleClass(task.teamRole)">
                    <text v-if="task.teamRole === 'leader'">👑 队长</text>
                    <text v-else-if="task.teamRole === 'member'">🤝 队员</text>
                    <text v-else>❓ 未知</text>
                  </text>
                </view>
                <view v-if="task.teamName" class="team-name-info">
                  <text class="team-label">团队名称：</text>
                  <text class="team-name">{{ task.teamName }}</text>
                </view>
                <view v-if="task.teamMembers && task.teamMembers.length > 0" class="team-members-info">
                  <text class="members-label">团队成员：</text>
                  <text class="members-count">{{ task.teamMembers.length }}人</text>
                </view>
              </view>
              
              <!-- 单人挑战详细信息 -->
              <view v-if="task.challengeType === 'single'" class="single-details">
                <text class="single-info">独立完成挑战任务</text>
              </view>
            </view>
          </view>
          
          <view class="task-card-footer">
            <view class="publisher-info-new" @click.stop="goToUserProfile(task.publisherId)">
              <img :src="getAvatarUrl(task.userAvatar)" class="publisher-avatar-new" @error="handleTaskAvatarError" />
              <view class="publisher-meta">
                <span class="publisher-name-new">{{ task.userName || userStore.profile?.nickname }}</span>
                <span class="org-name-new" 
                  v-if="task.orgName && task.creditCode" 
                  @click.stop="goToOrganization(task.creditCode)">
                  {{ task.orgName }}
                </span>
                <span class="org-name-new" v-else>{{ task.orgName || '未知企业' }}</span>
              </view>
            </view>
            <view class="task-meta">
              <span class="task-location">{{ getLocationName(task.adCode) || '未知地区' }}</span>
              <span class="task-distance">{{ task.distance || '未知距离' }}</span>
              <span class="task-badges">
                <template v-if="task.badges && task.badges.length">
                  <span 
                    v-for="badge in task.badges" 
                    :key="badge.id" 
                    class="badge-new"
                    :data-level="badge.level"
                    :title="`${getBadgeName(badge.association)} 等级 ${badge.level}`"
                  >
                    {{ getBadgeName(badge.association) }} Lv{{ badge.level }}
                  </span>
                </template>
                <template v-else>当前任务无徽章</template>
              </span>
            </view>
          </view>
        </view>
      </view>
      <!-- 空状态 -->
      <view v-else class="empty-state-new">
        <view class="empty-icon">📭</view>
        <view class="empty-title">暂无任务</view>
        <view class="empty-desc">您还没有相关的任务记录</view>
      </view>
    </view>
    <!-- 任务详情模态框 -->
    <view v-if="showModal" class="modal-mask" @tap.self="showModal = false">
      <view class="modal-content">
        <button class="modal-close" @tap="showModal = false">×</button>
        <text class="modal-title">{{ currentTask.title }}</text>
        <view class="modal-status" :class="statusClass(currentTask.status)"><text>{{ statusText(currentTask.status) }}</text></view>
        <view class="modal-row"><text>赏金：</text><text class="reward-amount">￥{{ currentTask.reward }}</text></view>
        <view class="modal-row"><text>截止日期：</text><text>{{ currentTask.deadline }}</text></view>
        <view class="modal-row modal-desc"><text>任务描述：</text><text>{{ currentTask.description }}</text></view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { onShow } from '@dcloudio/uni-app'

import { getBadgeNameByAssociation } from '@/utils/skillUtils'
import { calculateDistance } from '@/utils/geoUtils'
import { geoData, getAdcodeByDistrict, getLocationByAdcode } from "@/utils/geoUtils"
import { categories } from '@/utils/skillUtils'
import { useUserStore } from '@/store/user'
import { getAvatarUrl } from '@/utils/imageUtils.js'

// 丰富的三级联动数据结构
const userStore = useUserStore()
const defaultAvatar = ref("/static/images/default-avatar.png")
const loading = ref(false)
const cardActive = ref(null)
const rocketShake = ref(false)

const user = reactive({})
const filters = reactive({ keyword: '', status: '2', type: '' })
const tasks = ref([])
const showModal = ref(false)
const currentTask = ref({})
const tab = ref('published')

// 地区选择相关
const provinces = ref(geoData.map((province) => province.name));
const selectedProvince = ref("");
const cities = ref([]);
const districts = ref([]);
const selectedCity = ref("");
const selectedDistrict = ref("");
const selectedAdCode = ref("");
// 新增临时变量
const tempProvince = ref("");
const tempCity = ref("");
const tempDistrict = ref(null);

// 领域三级联动
const fields = ref(categories);
const selectedField = ref("");
const selectedCategory = ref("");
const selectedDirection = ref("");
const categoryList = ref([]);
const directions = ref([]);
const showRegionSelector = ref(false)

const allCities = computed(() => {
  if (!selectedProvince.value) return [];
  const province = geoData.find((p) => p.name === selectedProvince.value);
  return province ? province.cities.map((c) => c.name) : [];
});
const allDistricts = computed(() => {
  if (!selectedProvince.value || !selectedCity.value) return [];
  const province = geoData.find((p) => p.name === selectedProvince.value);
  const city = province?.cities.find((c) => c.name === selectedCity.value);
  return city ? city.districts.map((d) => d.name) : [];
});

const updatecategoryList = () => {
  const field = fields.value.find((f) => f.code === selectedField.value);
  if (field) {
    categoryList.value = field.subcategories.map((category) => ({
      name: category.name,
      code: category.code,
    }));
  } else {
    categoryList.value = [];
  }
  selectedCategory.value = "";
  directions.value = [];
  selectedDirection.value = "";
  fetchTasks();
};
const updateDirections = () => {
  const field = fields.value.find((f) => f.code === selectedField.value);
  const category = field?.subcategories.find((c) => c.code === selectedCategory.value);
  if (category) {
    directions.value = category.directions.map((direction) => ({
      name: direction.name,
      code: direction.code,
    }));
  } else {
    directions.value = [];
  }
  selectedDirection.value = "";
  fetchTasks();
};
const handleDirectionChange = () => { fetchTasks(); };

const getToken = () => uni.getStorageSync('accessToken') || ''

// 格式化日期时间方法（兼容iOS）
const formatDateTime = (dateTime) => {
	if (!dateTime) return '未设置';
	
	try {
		// 处理iOS不支持的日期格式
		let date;
		if (typeof dateTime === 'string') {
			// 将 "yyyy-MM-dd HH:mm:ss" 格式转换为 "yyyy-MM-ddTHH:mm:ss" 格式
			if (dateTime.includes(' ') && !dateTime.includes('T')) {
				dateTime = dateTime.replace(' ', 'T');
			}
		}
		date = new Date(dateTime);
		if (isNaN(date.getTime())) return '无效时间';
		
		const now = new Date();
		const diff = now.getTime() - date.getTime();
		const days = Math.floor(diff / (1000 * 60 * 60 * 24));
		
		// 如果是未来时间（截止时间），显示剩余天数
		if (diff < 0) {
			const remainingDays = Math.ceil(-diff / (1000 * 60 * 60 * 24));
			if (remainingDays === 1) return '明天截止';
			if (remainingDays <= 7) return `${remainingDays}天后截止`;
			return date.toLocaleDateString('zh-CN', { 
				month: 'short', 
				day: 'numeric',
				hour: '2-digit',
				minute: '2-digit'
			});
		}
		
		// 如果是过去时间（发布时间），显示相对时间
		if (days === 0) {
			const hours = Math.floor(diff / (1000 * 60 * 60));
			if (hours === 0) {
				const minutes = Math.floor(diff / (1000 * 60));
				return minutes <= 0 ? '刚刚发布' : `${minutes}分钟前发布`;
			}
			return `${hours}小时前发布`;
		}
		
		if (days === 1) return '昨天发布';
		if (days <= 7) return `${days}天前发布`;
		
		return date.toLocaleDateString('zh-CN', { 
			month: 'short', 
			day: 'numeric',
			hour: '2-digit',
			minute: '2-digit'
		});
	} catch (error) {
		console.error('时间格式化错误:', error);
		return '时间格式错误';
	}
};

function onSearch() {
  rocketShake.value = true;
  setTimeout(() => rocketShake.value = false, 400);
  fetchTasks();
}

function goToTaskDetail(taskId) { 
  // #ifdef H5
  window.open(`/pages/task/detail/index?id=${taskId}`); 
  // #endif
  // #ifdef MP-WEIXIN
  uni.navigateTo({
    url: `/pages/task/detail/index?id=${taskId}`
  });
  // #endif
}

const goToUserProfile = (userId) => { 
  // #ifdef H5
  window.open(`/profile?uid=${userId}`); 
  // #endif
  // #ifdef MP-WEIXIN
  // 先存储要查看的用户ID，然后跳转到个人页面
  uni.setStorageSync('routeUid', userId);
  uni.setStorageSync('viewOtherUser', 'true'); // 添加标记表示要查看其他用户
  uni.switchTab({
    url: `/pages/profile/index`
  });
  // #endif
};

// 跳转到企业页面
const goToOrganization = (creditCode) => {
  if (creditCode) {
    uni.navigateTo({
      url: `/pages/organization/index?id=${encodeURIComponent(creditCode)}`,
      fail: (err) => {
        console.error('跳转到企业页面失败:', err);
        uni.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  } else {
    uni.showToast({
      title: '该企业信息不完整',
      icon: 'none'
    });
  }
};

// 跳转到发布任务页面
const goToPublishTask = () => {
  uni.navigateTo({
    url: '/pages/task/publish/index',
    fail: (err) => {
      console.error('跳转失败:', err);
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      });
    }
  });
};

const currentLocation = ref({ latitude: 0, longitude: 0 });
const fetchCurrentLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      currentLocation.value.latitude = res.latitude;
      currentLocation.value.longitude = res.longitude;
      fetchTasks();
    },
    fail: () => { fetchTasks(); }
  });
};

function searchMyPublishedTasks(params, token) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: '${NETWORK_CONFIG.API_BASE_URL}/task/mypublish',
      method: 'GET',
      data: params,
      header: { 'Access-Token': `Bearer ${token}` }, // 使用后端要求的header名称
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          console.error('请求失败:', res.statusCode, res.data);
          // 返回空数据而不是拒绝Promise，避免UI报错
          resolve({
            tasks: [],
            totalPages: 0,
            currentPage: 0,
            message: `请求失败(${res.statusCode})`
          });
        }
      },
      fail: (err) => {
        console.error('请求发布任务列表失败:', err);
        // 返回空数据而不是拒绝Promise
        resolve({
          tasks: [],
          totalPages: 0, 
          currentPage: 0,
          message: '网络错误'
        });
      }
    });
  });
}
function searchMyChallengeTasks(params, token) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: '${NETWORK_CONFIG.API_BASE_URL}/task/mychallenge',
      method: 'GET',
      data: params,
      header: { 'Access-Token': `Bearer ${token}` }, // 使用后端要求的header名称
      success: (res) => resolve(res.data),
      fail: (err) => reject(err)
    });
  });
}

async function fetchTasks() {
  loading.value = true;
  
  // 检查用户store是否已初始化
  if (!userStore.isInitialized) {
    console.log('用户store未初始化，开始初始化...');
    try {
      await userStore.initialize();
    } catch (error) {
      console.error('用户store初始化失败:', error);
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      tasks.value = [];
      loading.value = false;
      return;
    }
  }
  
  // 获取用户信息
  const userId = userStore.profile?.uid;
  if (!userId) {
    console.error('用户ID不存在，无法获取任务');
    console.log('当前用户store状态:', {
      token: userStore.token,
      profile: userStore.profile,
      isLoggedIn: userStore.isLoggedIn
    });
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    tasks.value = [];
    loading.value = false;
    return;
  }

  console.log('获取任务参数:', {
    tab: tab.value,
    userId: userId,
    filters: filters,
    adCode: selectedAdCode.value,
    badges: selectedDirection.value || selectedCategory.value || selectedField.value
  });

  let params = {
    keyword: filters.keyword,
    status: filters.status,
    page: 0,
    size: 20,
    adCode: selectedAdCode.value || "",
    badges: selectedDirection.value || selectedCategory.value || selectedField.value || ""
  };
  
  let res;
  try {
    if (tab.value === 'published') {
      params.publisherId = userId;
      console.log('获取我发布的任务，参数:', params);
      res = await searchMyPublishedTasks(params, getToken());
    } else {
      params.challengerId = userId;
      console.log('获取我挑战的任务，参数:', params);
      res = await searchMyChallengeTasks(params, getToken());
    }

    console.log('API响应:', res);
    console.log('响应数据结构检查:', {
      hasRes: !!res,
      hasData: !!(res && res.data),
      hasTasks: !!(res && res.data && res.data.tasks),
      hasDirectTasks: !!(res && res.tasks),
      tasksLength: res?.data?.tasks?.length || res?.tasks?.length,
      tasksType: typeof (res?.data?.tasks || res?.tasks),
      isArray: Array.isArray(res?.data?.tasks || res?.tasks)
    });

    // 检查两种可能的数据结构：res.data.tasks 或 res.tasks
    const tasksData = (res && res.data && res.data.tasks) || (res && res.tasks);
    
    if (tasksData) {
      tasks.value = tasksData.map(t => {
        const task = typeof t === 'string' ? JSON.parse(t) : t;
        // 字段兼容
        task.userAvatar = task.userAvatar || task.publisherAvatar || task.challengerAvatar || '';
        task.userName = task.userName || task.publisherName || task.challengerName || '';
        task.orgName = task.orgName || task.organizationName || '';
        // 计算距离
        if (currentLocation.value.latitude && currentLocation.value.longitude && task.latitude && task.longitude) {
          task.distance = calculateDistance(
            currentLocation.value.latitude,
            currentLocation.value.longitude,
            task.latitude,
            task.longitude
          );
        } else {
          task.distance = "未知距离";
        }
        return task;
      });
      console.log('处理后的任务列表:', tasks.value);
    } else {
      console.log('没有找到任务数据，响应结构:', res);
      tasks.value = [];
    }
  } catch (error) {
    console.error('获取任务失败:', error);
    uni.showToast({
      title: '获取任务失败',
      icon: 'none'
    });
    tasks.value = [];
  }
  
  loading.value = false;
}

onMounted(async () => {
  console.log('页面加载，开始初始化...');
  
  // 确保用户store已初始化
  if (!userStore.isInitialized) {
    console.log('用户store未初始化，开始初始化...');
    try {
      await userStore.initialize();
      console.log('用户store初始化完成');
    } catch (error) {
      console.error('用户store初始化失败:', error);
      // 初始化失败时，fetchTasks会处理错误提示
    }
  }
  
  // 获取位置信息并获取任务
  fetchCurrentLocation();
  fetchTasks();
})

// 页面显示时刷新数据
onShow(() => {
  console.log('🔄 我的任务页面 onShow - 刷新数据');
  
  // 监听任务相关更新事件
  uni.$on('task-related-update', (data) => {
    console.log('🔄 我的任务页面收到任务相关更新事件:', data);
    // 刷新任务列表
    fetchTasks();
  });
  
  // 每次进入页面都刷新任务列表
  fetchTasks();
});

const getLocationName = (adCode) => {
  if (!adCode) return null;
  const location = getLocationByAdcode(adCode);
  if (location) {
    return `${location.province} ${location.city} ${location.district}`;
  }
  return null;
};

const openRegionSelector = () => {
  showRegionSelector.value = true;
  // 1. 省份
  if (selectedProvince.value) {
    tempProvince.value = selectedProvince.value;
  } else {
    tempProvince.value = provinces.value[0] || "";
  }
  // 2. 城市
  const provinceObj = geoData.find(p => p.name === tempProvince.value);
  if (selectedCity.value && provinceObj?.cities.some(c => c.name === selectedCity.value)) {
    tempCity.value = selectedCity.value;
  } else {
    tempCity.value = provinceObj?.cities[0]?.name || "";
  }
  // 3. 区县
  const cityObj = provinceObj?.cities.find(c => c.name === tempCity.value);
  if (selectedDistrict.value && cityObj?.districts.some(d => d.name === selectedDistrict.value)) {
    tempDistrict.value = cityObj.districts.find(d => d.name === selectedDistrict.value);
  } else {
    tempDistrict.value = cityObj?.districts[0] || null;
  }
};
function selectTempProvince(province) {
  tempProvince.value = province;
  tempCity.value = '';
  tempDistrict.value = null;
}
function selectTempCity(city) {
  tempCity.value = city;
  tempDistrict.value = null;
}
function selectTempDistrict(district) {
  tempDistrict.value = district;
}
function confirmRegion() {
  selectedProvince.value = tempProvince.value;
  selectedCity.value = tempCity.value;
  selectedDistrict.value = tempDistrict.value ? tempDistrict.value.name : "";
  if (tempDistrict.value && tempDistrict.value.adcode) {
    selectedAdCode.value = tempDistrict.value.adcode;
  } else if (tempCity.value) {
    const provinceObj = geoData.find(p => p.name === tempProvince.value);
    const cityObj = provinceObj?.cities.find(c => c.name === tempCity.value);
    selectedAdCode.value = cityObj?.adcode || "";
  } else if (tempProvince.value) {
    const provinceObj = geoData.find(p => p.name === tempProvince.value);
    selectedAdCode.value = provinceObj?.adcode || "";
  } else {
    selectedAdCode.value = "";
  }
  showRegionSelector.value = false;
  fetchTasks();
}
watch(showRegionSelector, (val) => {
  // #ifdef H5
  if (val) {
    document.body.style.overflow = 'hidden';
  } else {
    document.body.style.overflow = '';
  }
  // #endif
});

// 获取挑战类型文本
const getChallengeTypeText = (type) => {
  if (type === 'single') return '单人挑战';
  if (type === 'team') return '组队挑战';
  return '未知类型';
};

// 获取挑战类型class
const getChallengeTypeClass = (type) => {
  if (type === 'single') return 'challenge-type-single';
  if (type === 'team') return 'challenge-type-team';
  return 'challenge-type-unknown';
};

// 获取挑战类型徽章文本
const getChallengeTypeBadgeText = (type) => {
  if (type === 'single') return '个人';
  if (type === 'team') return '团队';
  return '未知';
};

// 获取挑战类型徽章class
const getChallengeTypeBadgeClass = (type) => {
  if (type === 'single') return 'badge-single';
  if (type === 'team') return 'badge-team';
  return 'badge-unknown';
};

// 获取角色class
const getRoleClass = (role) => {
  if (role === 'leader') return 'role-leader';
  if (role === 'member') return 'role-member';
  return 'role-unknown';
};

function statusText(status) {
  status = Number(status)
  switch (status) {
    case 0: return '待审核'
    case 1: return '已发布'
    case 2: return '进行中'
    case 3: return '已完成'
    default: return '未知'
  }
}
function statusClass(status) {
  status = Number(status)
  switch (status) {
    case 0: return 'status-pending'
    case 1: return 'status-published'
    case 2: return 'status-doing'
    case 3: return 'status-done'
    default: return 'status-unknown'
  }
}
function formatReward(reward) {
  if (!isNaN(reward)) {
    return Number(reward).toLocaleString();
  }
  return reward;
}
function getBadgeName(association) {
  return getBadgeNameByAssociation(association);
}

const showTypeSelector = ref(false)
const tempField = ref("")
const tempCategory = ref("")
const tempDirection = ref("")

// 打开弹窗时初始化临时变量
function openTypeSelector() {
  showTypeSelector.value = true
  tempField.value = selectedField.value || (fields.value[0]?.code ?? "")
  const fieldObj = fields.value.find(f => f.code === tempField.value)
  tempCategory.value = selectedCategory.value || (fieldObj?.subcategories[0]?.code ?? "")
  const categoryObj = fieldObj?.subcategories.find(c => c.code === tempCategory.value)
  tempDirection.value = selectedDirection.value || (categoryObj?.directions[0]?.code ?? "")
}

// 选择操作
function selectTempField(code) {
  tempField.value = code;
  tempCategory.value = '';
  tempDirection.value = '';
}
function selectTempCategory(code) {
  tempCategory.value = code;
  tempDirection.value = '';
}
function selectTempDirection(code) {
  tempDirection.value = code;
}

// 确认按钮
function confirmType() {
  selectedField.value = tempField.value;
  selectedCategory.value = tempCategory.value;
  selectedDirection.value = tempDirection.value;
  showTypeSelector.value = false;
  fetchTasks();
}

const statusOptions = ['状态', '待审核', '已发布', '进行中', '已完成'];
const statusIndex = ref(3); // 默认选中"进行中"（索引3）
function onStatusPickerChange(e) {
  statusIndex.value = e.detail.value;
  if (statusIndex.value == 0) filters.status = '';
  else if (statusIndex.value == 1) filters.status = '0';
  else if (statusIndex.value == 2) filters.status = '1';
  else if (statusIndex.value == 3) filters.status = '2';
  else if (statusIndex.value == 4) filters.status = '3';
  fetchTasks();
}
watch(() => filters.status, (val) => {
  if (val === '') statusIndex.value = 0;
  else if (val === '0') statusIndex.value = 1;
  else if (val === '1') statusIndex.value = 2;
  else if (val === '2') statusIndex.value = 3;
  else if (val === '3') statusIndex.value = 4;
});
const typeOptions = ['类型', '个人任务', '组队任务'];
const typeIndex = ref(0);
function onTypePickerChange(e) {
  typeIndex.value = e.detail.value;
  if (typeIndex.value == 0) filters.type = '';
  else if (typeIndex.value == 1) filters.type = 'individual';
  else if (typeIndex.value == 2) filters.type = 'team';
  fetchTasks();
}
watch(() => filters.type, (val) => {
  if (val === '') typeIndex.value = 0;
  else if (val === 'individual') typeIndex.value = 1;
  else if (val === 'team') typeIndex.value = 2;
});

// 新增横滑 chip 交互方法
function setStatus(status) {
  filters.status = status;
  fetchTasks();
}
function setType(type) {
  filters.type = type;
  fetchTasks();
}
// 类型chip显示文字
const getTypeLabel = computed(() => {
  if (selectedDirection.value) {
    const field = fields.value.find(f => f.code === selectedField.value);
    const category = field?.subcategories.find(c => c.code === selectedCategory.value);
    const direction = category?.directions.find(d => d.code === selectedDirection.value);
    return direction ? direction.name : '全部';
  } else if (selectedCategory.value) {
    const field = fields.value.find(f => f.code === selectedField.value);
    const category = field?.subcategories.find(c => c.code === selectedCategory.value);
    return category ? category.name : '全部';
  } else if (selectedField.value) {
    const field = fields.value.find(f => f.code === selectedField.value);
    return field ? field.name : '全部';
  }
  return '全部';
});

// 头像错误处理函数
const handleAvatarError = () => {
  console.log('用户头像加载失败，使用默认头像');
};

const handleTaskAvatarError = () => {
  console.log('任务头像加载失败，使用默认头像');
};
</script>

<style scoped>
.mytask-page {
  background: #F5F5F5;
  min-height: 100vh;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}
.header-bar-new {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #4A90E2;
  padding: 0 20px;
  height: 56px;
  color: #333;
  box-shadow: 0 2px 8px rgba(160,132,232,0.05);
}
.brand {
  font-size: 20px;
  font-weight: bold;
  letter-spacing: 2px;
}
.user-info {
  display: flex;
  align-items: center;
}
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 8px;
  object-fit: cover;
  background: #fff;
  border: 2px solid #e0cfff;
}
.nickname {
  font-size: 15px;
  font-weight: 500;
}
.search-area {
  display: flex;
  align-items: center;
  padding: 18px 16px 12px 16px;
  margin-bottom: 8px;
  background: #4A90E2;
}

/* 发布任务按钮样式 */
.publish-task-area {
  padding: 12px 16px;
  background: #fff;
  border-bottom: 1px solid #e0e0e0;
}

.publish-task-btn {
  width: 100%;
  height: 44px;
  background: linear-gradient(135deg, #2a6bda 0%, #1e4ba3 100%);
  border: none;
  border-radius: 8px;
  color: white;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(42, 107, 218, 0.3);
}

.publish-task-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(42, 107, 218, 0.4);
}

.publish-task-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(42, 107, 218, 0.3);
}

.publish-icon {
  font-size: 20px;
  font-weight: bold;
  line-height: 1;
}

.publish-text {
  font-size: 16px;
  font-weight: 600;
}

.search-container {
  display: flex;
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  /* 新增：让 input 和 btn 高度一致 */
  align-items: stretch;
}

.search-input,
.search-btn {
  height: 48px;
  box-sizing: border-box;
  border: none;
  outline: none;
  font-size: 16px;
  line-height: 48px;
  padding: 0 20px;
  background: #fff;
}

.search-input {
  border-radius: 24px 0 0 24px;
  flex: 1;
  border: 1px solid #d8c2ff;
  border-right: none;
}

.search-btn {
  border-radius: 0 24px 24px 0;
  width: 120px;
  background: linear-gradient(135deg, #4d8df5 0%, #2a6bda 100%);
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  border: 1px solid #d8c2ff;
  border-left: none;
  cursor: pointer;
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(110, 59, 255, 0.3);
  opacity: 0.95;
}

.search-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(110, 59, 255, 0.2);
}

.search-btn svg { /* 放大镜图标样式 */
  width: 18px;
  height: 18px;
  fill: white;
}
.rocket-icon {
  width: 22px; height: 22px; vertical-align: middle;
  transition: transform 0.2s;
}
.rocket-icon.shake {
  animation: rocket-shake 0.4s;
}
@keyframes rocket-shake {
  0% { transform: rotate(0); }
  20% { transform: rotate(-10deg);}
  40% { transform: rotate(10deg);}
  60% { transform: rotate(-8deg);}
  80% { transform: rotate(8deg);}
  100% { transform: rotate(0);}
}
.filter-section-new {
  background: #F5F5F5;
  padding: 8px 8px 0 8px;
}
.filter-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  align-items: center;
  margin-bottom: 12px;
}
.filter-buttons {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}
@media (max-width: 600px) {
  .filter-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
    margin-bottom: 8px;
  }
  .filter-buttons {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
}
@media (max-width: 400px) {
  .filter-grid {
    grid-template-columns: 1fr;
    gap: 6px;
  }
  .filter-buttons {
    grid-template-columns: 1fr;
    gap: 6px;
  }
}
.filter-select {
  height: 44px;
  line-height: 44px;
  text-align: center;
  font-size: 15px;
  padding: 0 36px 0 16px;
  border-radius: 20px;
  border: 1.5px solid #e0cfff;
  background: #FFFFFF;
  color: #333;
  appearance: none;
  background-image: url('data:image/svg+xml;utf8,<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg"><ellipse cx="11" cy="14" rx="7" ry="4" fill="%23e0cfff"/><ellipse cx="11" cy="11" rx="9" ry="6" fill="%23FFFFFF"/><ellipse cx="11" cy="13" rx="5" ry="3" fill="%23e0cfff"/></svg>');
  background-repeat: no-repeat;
  background-position: right 12px center;
  background-size: 22px 22px;
  transition: border 0.2s;
}
.filter-select option {
  text-align: center;
}
.filter-select:focus, .filter-select:active, .filter-select.active {
  border: 1.5px solid #c0a0ff;
}
.region-btn-new:focus, .region-btn-new:active {
  border: 1.5px solid #c0a0ff;
}
.tab-bar-new {
  display: flex;
  background: transparent;
  margin: 18px 0 18px 0;
  border-bottom: 1.5px solid #e0cfff;
  justify-content: space-between;
  align-items: flex-end;
  padding: 0 16px;
}
.tab-item-new {
  flex: 1 1 0;
  text-align: center;
  font-size: 18px;
  color: #333;
  font-weight: 500;
  padding: 8px 0 6px 0;
  cursor: pointer;
  position: relative;
  background: transparent;
  transition: color 0.2s;
  min-height: 44px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.tab-item-new.active {
  color: #4A90E2;
  font-weight: bold;
}
.tab-icon {
  width: 20px; height: 20px; vertical-align: middle; margin-bottom: 2px;
  filter: grayscale(1) opacity(0.5);
  transition: filter 0.3s;
}
.tab-icon.active {
  filter: none;
}
.tab-underline-new {
  width: 32px;
  height: 4px;
  background: #4A90E2;
  border-radius: 2px;
  transition: all 0.3s cubic-bezier(.4,0,.2,1);
}
.task-list-new {
  padding: 0 8px 16px 8px;
}
.task-card {
  border: 1.5px solid #e0cfff;
  background: #FFFFFF;
  border-radius: 20px;
  box-shadow: 0 4px 16px rgba(160,132,232,0.06);
  margin-bottom: 10px;
  padding: 16px;
  min-height: 44px;
  transition: box-shadow 0.2s, transform 0.1s;
  cursor: pointer;
}
.task-card:active {
  box-shadow: 0 1px 4px rgba(160,132,232,0.08);
}
.task-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.task-title-new {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0;
}
.task-salary-new {
  font-size: 15px;
  color: #4A90E2;
  font-weight: bold;
}
.task-desc-new {
  font-size: 14px;
  color: #444;
  margin-bottom: 10px;
  min-height: 20px;
  line-height: 1.4;
}

/* 任务时间信息样式 */
.task-time-info {
  margin: 8px 0;
  padding: 8px 0;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
}

.time-item {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
}

.time-item:last-child {
  margin-bottom: 0;
}

.time-icon {
  margin-right: 6px;
  font-size: 12px;
}

.time-label {
  margin-right: 4px;
  font-weight: 500;
  color: #555;
}

.time-value {
  color: #333;
  font-weight: 400;
}
.task-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  gap: 8px;
}
.publisher-info-new {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: transform 0.1s;
}
.publisher-info-new:active {
  transform: scale(0.98);
}
.publisher-avatar-new {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  margin-right: 6px;
  object-fit: cover;
  background: #fff;
  border: 2px solid #e0cfff;
}
.publisher-meta {
  display: flex;
  flex-direction: column;
}
.publisher-name-new {
  font-size: 13px;
  font-weight: 500;
  color: #333;
}
.org-name-new {
  font-size: 12px;
  color: #888;
  cursor: pointer;
  transition: color 0.2s;
}

.org-name-new:hover {
  color: #007AFF;
  text-decoration: underline;
}
.task-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 2px;
}
.task-location, .task-distance {
  font-size: 12px;
  color: #888;
}
.task-badges {
  font-size: 12px;
  color: #4A90E2;
  margin-top: 2px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
}
.badge-new {
  display: inline-flex;
  align-items: center;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border: 2px solid transparent;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  margin-right: 4px;
}

.badge-new::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s;
}

.badge-new:hover::before {
  left: 100%;
}

.badge-new:hover {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
  border-color: rgba(255, 255, 255, 0.5);
}

/* 不同等级的徽章样式 */
.badge-new[data-level="1"] {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
}

.badge-new[data-level="2"] {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.badge-new[data-level="3"] {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
}

.badge-new[data-level="4"] {
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
}

.badge-new[data-level="5"] {
  background: linear-gradient(135deg, #a18cd1 0%, #fbc2eb 100%);
}

/* 特殊徽章样式 */
.badge-new[data-level="6"] {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  animation: badgeGlow 2s ease-in-out infinite alternate;
}

.badge-new[data-level="7"] {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  animation: badgePulse 1.5s ease-in-out infinite;
}

.badge-new[data-level="8"] {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  animation: badgeShine 3s ease-in-out infinite;
}

.badge-new[data-level="9"] {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  animation: badgeFloat 2s ease-in-out infinite;
}

.badge-new[data-level="10"] {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  animation: badgeRainbow 4s linear infinite;
}

/* 徽章动画效果 */
@keyframes badgeGlow {
  0% { box-shadow: 0 2px 8px rgba(255, 154, 158, 0.3); }
  100% { box-shadow: 0 4px 20px rgba(255, 154, 158, 0.6); }
}

@keyframes badgePulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.05); }
}

@keyframes badgeShine {
  0% { background-position: -200% center; }
  100% { background-position: 200% center; }
}

@keyframes badgeFloat {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-3px); }
}

@keyframes badgeRainbow {
  0% { filter: hue-rotate(0deg); }
  100% { filter: hue-rotate(360deg); }
}

/* 徽章图标 */
.badge-new::after {
  content: '🏆';
  margin-left: 4px;
  font-size: 10px;
  opacity: 0.8;
}
.empty-state-new {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 220px;
  color: #b0b0b0;
  background: #f9f0ff;
  border-radius: 20px;
  margin: 24px 0;
  padding: 32px 0;
}
.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}
.empty-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 6px;
}
.empty-desc {
  font-size: 14px;
  color: #aaa;
}
.loading-spinner {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 180px;
}
.spinner {
  width: 36px;
  height: 36px;
  border: 4px solid #e0cfff;
  border-top: 4px solid #4A90E2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.modal-mask {
  position: fixed;
  left: 0; right: 0; top: 0; bottom: 0;
  background: rgba(0,0,0,0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.modal-content {
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 2px 16px rgba(160,132,232,0.12);
  max-width: 90vw;
  width: 380px;
  padding: 28px 20px 20px 20px;
  position: relative;
  animation: modal-pop 0.25s;
}
@keyframes modal-pop {
  0% { transform: scale(0.9); opacity: 0; }
  100% { transform: scale(1); opacity: 1; }
}
.modal-close {
  position: absolute;
  right: 16px;
  top: 12px;
  background: none;
  border: none;
  font-size: 28px;
  color: #aaa;
  cursor: pointer;
}
.modal-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}
.modal-status {
  display: inline-block;
  padding: 2px 12px;
  border-radius: 12px;
  font-size: 13px;
  font-weight: 500;
  margin-bottom: 10px;
}
.modal-status.status-pending { background: #fffbe6; color: #e6a23c; }
.modal-status.status-published { background: #e6f0fa; color: #4A90E2; }
.modal-status.status-doing { background: #f3e6fa; color: #4A90E2; }
.modal-status.status-done { background: #e6f9f0; color: #67c23a; }
.modal-row {
  font-size: 15px;
  margin-bottom: 8px;
  color: #444;
}
.modal-desc {
  color: #666;
  font-size: 14px;
}
.region-popup-mask {
  position: fixed;
  left: 0; right: 0; top: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  z-index: 9999;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}
.region-popup {
  width: 100vw;
  max-width: 480px;
  margin: 0 auto;
  background: #fff;
  border-radius: 24px 24px 0 0;
  box-shadow: 0 -4px 24px #e0c3fc33;
  animation: popup-slide-up 0.25s cubic-bezier(.4, 0, .2, 1);
  z-index: 10000;
  padding-bottom: 16px;
  

}
@keyframes popup-slide-up {
  0% { transform: translateY(100%); opacity: 0; }
  100% { transform: translateY(0); opacity: 1; }
}
.region-picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px 8px 16px;
  border-bottom: 1px solid #f0f0f0;
}
.region-picker-title {
  font-weight: bold;
  font-size: 16px;
}
.region-picker-cancel, .region-picker-confirm {
  color: #4A90E2;
  font-size: 15px;
  cursor: pointer;
}
.region-columns {
  display: flex;
  gap: 0;
  padding: 0 8px;
}
.region-list-wrapper {
  position: relative;
  flex: 1;
  min-width: 0;
  max-height: 300px;
  height: 300px;
  overflow: hidden;
  background: #fff;
}
.region-list {
  height: 100%;
  overflow-y: auto;
  padding: 0;
  margin: 0;
  list-style: none;
}
.region-list li {
  padding: 12px 0;
  text-align: center;
  cursor: pointer;
  border-radius: 12px;
  transition: background 0.2s, color 0.2s;
  font-size: 15px;
}
.region-list li.active {
  background: #4A90E2 !important;
  color: #fff !important;
  font-weight: bold;
}
.region-list li:hover {
  background: #e0cfff;
}
.gradient-top,
.gradient-bottom {
  position: absolute;
  left: 0;
  right: 0;
  height: 24px;
  pointer-events: none;
  z-index: 2;
}
.gradient-top {
  top: 0;
  background: linear-gradient(to bottom, #fff, rgba(255,255,255,0));
}
.gradient-bottom {
  bottom: 0;
  background: linear-gradient(to top, #fff, rgba(255,255,255,0));
}
@media (max-width: 600px) {
  .header-bar-new { height: 48px; padding: 0 8px; font-size: 16px; }
  .avatar { width: 32px; height: 32px; }
  .nickname { font-size: 13px; }
  .search-area { padding: 12px 6px 8px 6px; }
  .search-input, .search-btn { height: 36px; font-size: 14px; }
  .task-card { padding: 10px 6px 6px 6px; min-height: 44px; }
  .task-title-new { font-size: 14px; }
  .tab-bar-new { padding: 0 4px; font-size: 14px; }
  .tab-item-new { font-size: 14px; padding: 6px 0 4px 0; }
  .tab-underline-new { width: 18px; height: 2px; }
  .publisher-avatar-new { width: 20px; height: 20px; }
  .publisher-name-new { font-size: 11px; }
  .org-name-new, .task-location, .task-distance, .task-badges { font-size: 10px; }
  
  /* 移动端发布任务按钮适配 */
  .publish-task-area { padding: 8px 12px; }
  .publish-task-btn { height: 40px; font-size: 15px; }
  .publish-icon { font-size: 18px; }
  .publish-text { font-size: 15px; }

/* 手机端徽章适配 */
@media (max-width: 768px) {
  .task-badges {
    gap: 4px;
  }

  .badge-new {
    padding: 4px 10px;
    font-size: 11px;
    border-radius: 16px;
    letter-spacing: 0.3px;
  }

  .badge-new::after {
    font-size: 9px;
    margin-left: 3px;
  }
}

@media (max-width: 480px) {
  .badge-new {
    padding: 3px 8px;
    font-size: 10px;
    border-radius: 14px;
  }

  .badge-new::after {
    font-size: 8px;
    margin-left: 2px;
  }
}
  .modal-content { width: 96vw; padding: 16px 6px 10px 6px; }
  .modal-title { font-size: 15px; }
  .region-list-wrapper { max-height: 180px; height: 180px; }
  .region-list li { font-size: 13px; padding: 8px 0; }
}
.scrollable-filters {
  display: flex;
  gap: 8px;
  padding: 8px 16px;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  margin-bottom: 12px;
}
.filter-chip {
  flex-shrink: 0;
  padding: 6px 14px;
  border-radius: 16px;
  background: #f1f3f5;
  border: 1px solid #e0e0e0;
  font-size: 15px;
  color: #333;
  cursor: pointer;
  transition: background 0.2s, color 0.2s;
  white-space: nowrap;
}
.filter-chip.active {
  background: #2a6bda;
  color: white;
  border-color: transparent;
}

/* 挑战类型信息样式 */
.challenge-type-info {
  margin: 12px 0;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 1px solid #e0e0e0;
}

.challenge-type-card {
  background: white;
  border-radius: 10px;
  padding: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.challenge-type-card.challenge-type-single {
  border-left: 4px solid #52c41a;
}

.challenge-type-card.challenge-type-team {
  border-left: 4px solid #1890ff;
}

.challenge-type-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.challenge-type-icon {
  font-size: 24px;
  margin-right: 8px;
}

.challenge-type-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.challenge-type-badge {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.challenge-type-badge.badge-single {
  background: #e8f5e9;
  color: #52c41a;
}

.challenge-type-badge.badge-team {
  background: #e3f2fd;
  color: #1890ff;
}

.team-details, .single-details {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px dashed #e0e0e0;
}

.team-role-info, .team-name-info, .team-members-info {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  font-size: 14px;
}

.role-label, .team-label, .members-label {
  color: #666;
  margin-right: 8px;
  min-width: 70px;
}

.role-value {
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 6px;
}

.role-value.role-leader {
  background: #fff7e6;
  color: #fa8c16;
}

.role-value.role-member {
  background: #e8f5e9;
  color: #52c41a;
}

.team-name {
  font-weight: 600;
  color: #1890ff;
}

.members-count {
  font-weight: 600;
  color: #1890ff;
}

.single-info {
  font-size: 13px;
  color: #666;
  font-style: italic;
}

/* 响应式样式 */
@media (max-width: 768px) {
  .challenge-type-info {
    margin: 10px 0;
    padding: 10px;
  }
  
  .challenge-type-card {
    padding: 10px;
  }
  
  .challenge-type-icon {
    font-size: 20px;
  }
  
  .challenge-type-title {
    font-size: 14px;
  }
  
  .challenge-type-badge {
    padding: 3px 8px;
    font-size: 11px;
  }
  
  .team-role-info, .team-name-info, .team-members-info {
    font-size: 13px;
  }
  
  .role-label, .team-label, .members-label {
    min-width: 60px;
    font-size: 12px;
  }
}
</style>
